<template>
  <div class="purchase_view">
    <!-- 添加或修改申请采购明细对话框 -->
    <el-button type="primary" @click="handleAdd" style="float: right; margin-top: -55px;" size="mini"
    v-hasPermi="['labdanger:occupation:edit']">新建领用</el-button>
    <el-dialog :title="title" center :visible.sync="open" width="860px" append-to-body>
      <el-tabs v-model="activeName">
      <el-tab-pane label="流程表单" name="first"></el-tab-pane>
      <el-tab-pane label="流程导入" name="second" v-if="detailsList.length>0">
        <FlowChoose ref="workFlow" @workflow="setWorkflow" :businessType="form.businessTypeOpt"></FlowChoose>
      </el-tab-pane>
    </el-tabs>
       <el-form ref="form" :model="form" :rules="rules" label-width="100px" v-if="activeName=='first'">
        <el-form-item style="margin-top: 0" label="流程创建" prop="createUserId">
          <span style="color: #0000ee">{{form.createTime}} {{form.createBy}}创建</span>
          <div style="float:right;">
              <el-button
              :class="showCopy?'active dis_active':'active'"
              type="text"
              @click="showCopy=showCopy?false:true"
          >新建抄送</el-button>
            </div>
        </el-form-item>

        <el-form-item label="任务抄送" prop="checkedUserList" v-if="showCopy">
          <div class="purchase_s_view">
            <el-select v-model="checkedUserList" @remove-tag="removeCheckUser" multiple placeholder="请选择任务抄送" clearable style="width: 100%"></el-select>
            <ChooseUser @chooseUsers="getUser" ></ChooseUser>
          </div>
        </el-form-item>
        <el-form-item label="流程名称" prop="flowName">
          <el-input
          placeholder="请输入流程名称"
          clearable
          v-model="form.flowName"
          size="small"
        />
        </el-form-item>
        <el-row>
            <el-col :span="12">
                <el-form-item label="申领日期" prop="applyDate">
                  <el-input
                    class="input_w"
                    placeholder="请选择申领老师"
                    v-model="form.applyDate"
                    size="small"
                    disabled
                    />
                </el-form-item>
            </el-col>
            <el-col :span="12">
               <el-form-item label="申领老师" prop="applyTeacherName">
                    <div class="purchase_s_view">
                    <el-input
                      class="input_w"
                      placeholder="请选择申领老师"
                      v-model="form.applyTeacherName"
                      size="small"
                      disabled
                      />
                      <ChangeTeacher  v-if="!detailsList.length" @change-teacher="setApplyTeacher"></ChangeTeacher>
                      </div>
                </el-form-item>
            </el-col>
        </el-row>
        <el-row>
            <el-col :span="12">
                <el-form-item label="存放单位" prop="collegeId">
                  <el-select
                    class="input_w"
                    v-model="form.collegeId"
                    placeholder="请选择二级单位"
                    size="small"
                    @change="handleLabChange">
                    <el-option v-for="item in secondOrgList" :key="item.orgName" :label="item.orgName" :value="item.orgId">
                    </el-option>
                  </el-select>
                </el-form-item>
            </el-col>
            <el-col :span="12">
               <el-form-item
                  label="存放实验室"
                  prop="labId"
                  size="small">
                  <el-select
                    class="input_w"
                    v-model="form.labId"
                    placeholder="请选择实验室"
                    @change="refreshChoose">
                    <el-option v-for="item in secondOrgLabList" :key="item.orgName" :label="item.orgName"
                      :value="item.orgId">
                    </el-option>
                  </el-select>
                </el-form-item>
            </el-col>
        </el-row>
        <el-row>
            <el-col :span="12">
                <el-form-item label="老师认证" prop="teacherVerify1Name">
                    <div class="purchase_s_view">
                      <el-input
                        class="input_w"
                        placeholder=""
                        v-model="form.teacherVerify1Name"
                        clearable
                        size="small"
                        disabled
                        />
                        <AuthTeacher @auth-teacher="setAuthTeacher" :employeeNo="form.applyTeacherNo"></AuthTeacher>
                    </div>
                </el-form-item>
            </el-col>
            <el-col :span="12">
                <el-form-item label="库存老师" prop="teacherVerify2Name">
                    <div class="purchase_s_view">
                      <el-input
                        class="input_w"
                        placeholder=""
                        v-model="form.teacherVerify2Name"
                        clearable
                        size="small"
                        disabled
                        />
                        <AuthTeacherNew @auth-teacher="setAuthTeacherNew"></AuthTeacherNew>
                    </div>
                </el-form-item>
            </el-col>
        </el-row>
        <el-row>
             <el-col :span="12">
              <el-form-item label="委托领取" prop="entrusted1Name">
                  <div class="purchase_s_view">
                    <el-input
                      class="input_w"
                      placeholder=""
                      v-model="form.entrusted1Name"
                      clearable
                      size="small"
                      disabled
                      />
                      <AuthorizeItem index='1' @change-entrusted="setEntrusted"></AuthorizeItem>
                  </div>
              </el-form-item>
          </el-col>
          <el-col :span="12">
              <el-form-item label="委托领取" prop="entrusted2Name">
                  <div class="purchase_s_view">
                    <el-input
                      class="input_w"
                      placeholder=""
                      v-model="form.entrusted2Name"
                      clearable
                      size="small"
                      disabled
                      />
                      <AuthorizeItem index='2' @change-entrusted="setEntrusted"></AuthorizeItem>
                  </div>
              </el-form-item>
          </el-col>
        </el-row>
      </el-form>

    <div v-if="activeName=='first' && form.instanceId">
      <el-row>
          <el-col :span="12">
              <h4 style="margin-top: 10px; height: 0">申领试剂</h4>
          </el-col>
          <el-col :span="12">
              <div style="float:right;" class="purchase_s_view">
              <AddAgentia @list ="getList" ref="addAgentia" :instanceId="form.instanceId"
              :applyTeacherNo="form.applyTeacherNo"
              :applyTeacherName="form.applyTeacherName"
              :kindsOptions="kindsOptions" :unitOptOptions="unitOptOptions" ></AddAgentia>
              </div>
          </el-col>
      </el-row>
      <el-table style="width: 100%; margin-bottom: 20px; margin-top: -15px" :data="detailsList">
          <el-table-column label="编号" align="center" prop="occupationDetailsId" width="60"/>
          <el-table-column label="名称"  prop="materialName" :show-overflow-tooltip="true"/>
          <el-table-column label="Cas号" align="center" prop="casNo" width="100"/>
          <el-table-column label="类别" align="center" prop="hazardousOpt" :formatter="kindsFormat" width="100"/>
          <el-table-column label="规格" align="center" prop="model" width="100"/>
          <el-table-column label="单位" align="center" prop="unitOpt" :formatter="unitOptFormat" width="60"/>
          <el-table-column label="领用数量" align="center" prop="occupationQuantity" width="60"/>
          <el-table-column label="操作" align="center"  width="60">
            <template slot-scope="scope">
                <el-button
                  size="mini"
                  class="active"
                  type="text"
                  @click="handleDeleteDetail(scope.row)"
                  v-hasPermi="['labdanger:details:edit']"
                >移除</el-button>
            </template>
          </el-table-column>
        </el-table>
        <pagination
          v-show="total>0"
          :total="total"
          :page.sync="queryParams.pageNum"
          :limit.sync="queryParams.pageSize"
          @pagination="getList"
        />
      </div>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm" v-if="activeName=='first'" v-hasPermi="['labdanger:occupation:edit']">保存</el-button>
        <el-button type="primary" @click="submitWorkflow" v-if="activeName=='second'" v-hasPermi="['labdanger:occupation:edit']">提交</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { searchEmployee } from "@/api/labdata/employee";
import { getCheckedList } from "@/api/labdata/employee";
import FlowChoose from '@/views/labdata/flowDefination/flow_choose.vue'
import { getAllRestrictedKinds } from "@/api/labdata/cylindersType";
import { getOccupation, addOccupation, updateOccupation, submitOccupation } from "@/api/labdanger/occupation";
import { listDetails, delDetails } from "@/api/labdanger/occupationDetail";
import ChooseUser from "@/views/labsafety/safetyCompents/check_user.vue"
import AddAgentia from './occupation/addAgentia.vue'
import ChangeTeacher from './occupation/changeTeacher.vue'
import AuthTeacher from './occupation/authTeacher.vue'
import AuthTeacherNew from './occupation/authTeacherNew.vue'
import AuthorizeItem from './occupation/authorizeItem.vue'
import { formatCurrentDate } from "@/utils/index";
import { getOrgByFunctionOpt, listSecondOrgLab } from "@/api/labdata/orgnization";
export default {
  components: {
    ChooseUser,
    AddAgentia,
    ChangeTeacher,
    AuthTeacher,
    AuthTeacherNew,
    AuthorizeItem,
    FlowChoose
  },
  name: "OccupationDialog",
  data() {
    return {
      allUserList: [],
      checkedUserList: [],
      activeName: 'first',
      initApplyDate:null,
      // 遮罩层
      // 总条数
      total: 0,
      showCopy: false,
      //二级机构
      secondOrgList: [],
      //二级机构下的实验室
      secondOrgLabList: [],
      // 申请采购明细表格数据
      detailsList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 类别字典
      kindsOptions: [],
      // 单位字典
      unitOptOptions: [],
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 100,
        instanceId: null,
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        flowName: {required: true, message: '流程名称不能为空', trigger: 'blur'},
        applyDate: {required: true, message: '申领日期不能为空', trigger: 'blur'},
        applyTeacherName: {required: true, message: '申领老师不能为空', trigger: 'change'},
        collegeId: {required: true, message: '存放单位不能为空', trigger: 'change'},
        // labId: {required: true, message: '存放实验室不能为空', trigger: 'change'},
        teacherVerify1Name: {required: true, message: '老师认证不能为空', trigger: 'change'},
       // teacherVerify2Name: {required: true, message: '老师认证不能为空', trigger: 'change'},
        entrusted1Name: {required: true, message: '委托领取不能为空', trigger: 'change'},
        entrusted2Name: {required: true, message: '委托领取不能为空', trigger: 'change'}
      }
    };
  },
  created() {
    this.getAllKinds();
    this.getDicts("applyStatusOpt").then(response => {
        this.applyStatusOptOptions = response.data;
    });
    this.getDicts("unitOpt").then(response => {
      this.unitOptOptions = response.data;
    });
    getOrgByFunctionOpt(2).then(response => {
      this.secondOrgList = response.data;
    });
    this.getConfigKey("labdanger.occupation.ApplyDate").then(response => {
      this.initApplyDate = response.msg;
    });
  },
  methods: {
    setWorkflow(workflowId){
      this.form.workflowId = workflowId;
    },
    submitWorkflow(){
		if(!this.form.workflowId){
		  this.form.workflowId = this.$refs["workFlow"].getWorkflowId();
		}
        submitOccupation(this.form).then(response => {
          this.msgSuccess("修改成功");
          this.open = false;
          this.$emit("refresh");
        });
    },
    getAllKinds(){
      getAllRestrictedKinds().then(response => {
        this.kindsOptions = response.data;
      });
    },
    kindsFormat(row, column){
      for(let i=0; i<this.kindsOptions.length;i++){
        if(this.kindsOptions[i].kindsId == row.hazardousOpt){
          return this.kindsOptions[i].name;
        }
      }
      return '';
    },
    // 单位字典翻译
    unitOptFormat(row, column) {
      return this.selectDictLabel(this.unitOptOptions, row.unitOpt);
    },
    setApplyTeacher(data) {
      this.form.applyTeacherNo = data.employeeNo
      this.form.applyTeacherName = data.nickName
      this.$forceUpdate();
    },
    setEntrusted(data, index) {
      if (index == '1') {
        this.form.entrusted1No = data.employeeNo
        this.form.entrusted1Name = data.nickName
      } else {
        this.form.entrusted2No = data.employeeNo
        this.form.entrusted2Name = data.nickName
      }
      this.$forceUpdate();
    },
    setAuthTeacher(data) {
      this.form.teacherVerify1No = data.employeeNo
      this.form.teacherVerify1Name = data.nickName
      this.$forceUpdate();
    },
    setAuthTeacherNew(data) {
      this.form.teacherVerify2No = data.employeeNo
      this.form.teacherVerify2Name = data.nickName
      this.$forceUpdate();
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        instanceId: null,
        createTime: null,
        createBy: null,
        applyDate: null,
        collegeId: null,
        labId: null,
        applyTeacherNo: null,
        applyTeacherName: null,
        entrustedNo: null,
        entrustedName: null,
        teacherVerify: null,
        teacherVerify2: null
      };
      this.allUserList = [],
      this.checkedUserList = [],
      this.detailsList = [];
      this.resetForm("form");
      this.showCopy = false
      this.activeName = 'first';
      this.form.createTime  = formatCurrentDate();
      this.form.createBy = this.$store.state.user.name;
      this.form.applyTeacherName = this.$store.state.user.nickName;
      this.form.applyTeacherNo = this.$store.state.user.name;
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.form.createTime  = formatCurrentDate()
      this.form.applyDate = this.initApplyDate;
      const currentUsername = this.$store.state.user.name
      this.form.createBy = currentUsername
      searchEmployee(currentUsername).then(response => {
        let searchResult = response.data;
        if (searchResult && searchResult.length == 1) {
          this.form.applyTeacherNo = searchResult[0].employeeNo
          this.form.applyTeacherName = searchResult[0].nickName
        }
        //强制刷新
        this.$forceUpdate();
      });
      this.open = true;
      this.title = "新建领用表单";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
       this.reset();
       this.open = true;
       const instanceId = row.instanceId
        getOccupation(instanceId).then(response => {
          this.form = response.data;
          this.getLabOrgs()
          if(this.form.copyToUsers){
            getCheckedList({checkedUserIds:this.form.copyToUsers}).then(res=>{
              this.getUser(res.data)
              this.showCopy = true
            });
          }
          this.queryParams.instanceId = instanceId;
          this.title = "修改领用表单";
          this.getList();
        });
    },
    getLabOrgs() {
      listSecondOrgLab(this.form.collegeId).then(response => {
        this.secondOrgLabList = response.data;
        this.refreshChoose()
      });
    },
    getList() {
      this.loading = true;
      listDetails(this.queryParams).then(response => {
        this.detailsList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.instanceId != null) {
            updateOccupation(this.form).then(response => {
              this.msgSuccess("修改成功");
              this.getList();
              if(this.detailsList.length>0){
                this.activeName = "second";
              }
            });
          } else {
            addOccupation(this.form).then(response => {
              this.msgSuccess("新增成功");
              this.form = response.data;
              this.queryParams.instanceId = this.form.instanceId;
              this.getList();
              this.$forceUpdate();
            });
          }
          this.$emit("refresh")
        }
      });
    },
    handleEdit(row) {
      this.editItem = JSON.parse(JSON.stringify(row))
    },
    /** 编辑按钮操作 */
    handleUpdateDetail(row) {
      this.$refs["addAgentia"].updateDetail(row);
    },
    /** 删除按钮操作 */
    handleDeleteDetail(row) {
      const id = row.occupationDetailsId
      this.$confirm('是否确认删除申请采购明细编号为"' + id + '"的数据项?', "警告", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        }).then(function() {
          return delDetails(id);
        }).then(() => {
          this.getList();
          this.msgSuccess("删除成功");
        })
    },
    handleLabChange(item) {
      //console.log('change lab :'+item);
      if (item) {
        this.form.labId = null;
        listSecondOrgLab(item).then(response => {
          this.secondOrgLabList = response.data;
          this.refreshChoose()
        });
      }
    },
    refreshChoose() {
      this.$forceUpdate();
    },
    getUser(list) {
      this.allUserList = list
      this.checkedUserList = []
      this.form.copyToUsers = '';
      list.forEach((item, index) => {
        this.checkedUserList.push(item.nickName)
        if (index > 0) {
          this.form.copyToUsers += ','
        }
        this.form.copyToUsers += item.userId
      });
    },
    removeCheckUser(value) {
      let userId = this.allUserList.find(item => item.nickName == value).userId
      let array = this.form.copyToUsers.split(',')
      let index = array.indexOf(userId + '')
      array.splice(index, 1)
      this.form.copyToUsers = array.toString()
      //console.log(this.form.copyToUsers)
    }
  }
};
</script>

<style scoped>
.el-button.active{
    text-decoration: underline;
    color: #0000ee;
  }
  .el-button.dis_active {
    color: #999999
  }
  .purchase_s_view {
    display: flex;
    flex-direction: row;
    align-items: left;
    justify-content: left;
  }
  .input_w{
    width: 200px;
  }
</style>
